package com.qf.electronic.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class IdGenerator {

//    private static AtomicLong COUNTER = new AtomicLong(0);

    public static final String TOWER_KEY = "tower";

    public static final String LINE_KEY = "line";

    public static final String TOWER_PREFIX = "T";

    public static final String LINE_PREFIX = "L";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 生成指定长度的ID
     * @param prefix ID的前缀
     * @param length ID的长度
     * @return
     */
    public String generateId(String prefix, String key, int length){
        //先自加1，然后将最后得到的结果返回，这个是通过CAS乐观锁来保证的线程安全
        //但是这种设计有一个弊端，就是服务器重启之后，计数重新归0，我们可以考虑使用
        //redis来完成计数的增加 redis提供了incr指令来对存储的数字进行增加
//        long l = COUNTER.incrementAndGet();
        Long number = redisTemplate.opsForValue().increment(key);
        int lenOfNumber = length -  prefix.length();
        StringBuilder builder = new StringBuilder(prefix);
        while (lenOfNumber > 0){
            builder.append("0");
            lenOfNumber --;
        }
        builder.append(number);
        return builder.toString();
    }
}
